<template>
  <div class="wh-100  d-flex fs-14" v-loading="loading">
    <!--左边-->
    <div  class="h-100 flex-1 w-0  py-12 px-12" style="background-color: #ffffff">
      <!--头部-->
      <div class="d-flex-between-center ch60" >
        <div>
          <Button type="primary" @click="handleAdd">添加账号</Button>
          <Button @click="handleDel(2)">批量删除</Button>
          <Button @click="handleResetPassword">重置用户密码</Button>
          <Button @click="handleExportSelection">导出所选数据</Button>
          <Button @click="handleExportAll">导出全部数据</Button>
        </div>
        <check-password ref="checkPass" @on-success="resetPass" />
        <div>
          <Button class="cw40"  :icon="showRight ? `ios-arrow-forward` : `ios-arrow-back`" @click.native="showRight = !showRight" type="primary"></Button>
        </div>


      </div>
      <!--表格-->
      <div class=" bor-base-b ch02" v-ref-height="refHeight"  >
        <!--数据-->
        <Table  class="mt-12"  :columns="tableColumns" :height="refHeight.value" :data="tableData" @on-selection-change="selectChange">
          <template slot="status" slot-scope="{ row, index }">
            <Badge status="error" v-if="row.forbidden === '-1'" text="禁用" />
            <Badge status="success" v-else text="启用" />
          </template>
          <template slot-scope="{ row, index }" slot="action">
            <a class="table-btn mr-12" @click="editData(row)">编辑</a>
            <a class="table-btn mr-12" @click="forbidden(row)" v-if="row.forbidden === '0'">禁用</a>
            <a class="table-btn mr-12" @click="forbidden(row)" v-if="row.forbidden === '-1'">启用</a>
            <a class="table-btn"  @click="deleteData(row)">删除</a>
          </template>
        </Table>
      </div>
      <!--分页-->
      <div class=" d-flex-center ch60" >
        <Page
            :current="searchForm.pageNumber"
            :total="total"
            :page-size="searchForm.pageSize"
            @on-change="changePage"
            @on-page-size-change="changePageSize"
            :page-size-opts="[10, 20, 50, 100, 200]"
            size="small"
            show-total
            show-elevator
            show-sizer
        ></Page>
      </div>
    </div>
    <!--右边-->
    <div class="h-100  ml-12 px-12 cw400" :class="!showRight ? 'hidden-table' : 'edit-table'" >
      <div class="bor-base-b ch03 cscolle" >
        <div class="fw-6 d-flex ch60" style="align-items: center;">
          {{rightTitle}}
        </div>
        <div v-if="showType ==1 || showType == 2" class="ml-24 mr-12 ">
          <Form ref="formRef"
                :model="formValidate"
                :rules="ruleValidate"
                :label-width="labelWidth80">
            <FormItem label="市场名称" prop="submarketCode" key="1" :rules="[{ required: true, message: '请选择市场', trigger: 'change' }]">
              <Select v-model="formValidate.submarketCode" @on-change="changeBackTask" clearable placeholder="请选择市场名称">
                <Option v-for="(item,index) in marketList" :value="item.submarketCode" :key="item.id">{{ item.submarketName }}</Option>
              </Select>
            </FormItem>
            <FormItem label="账号" prop="account" key="2" :rules="[{ required: true, message: '账号不能为空', trigger: 'blur' }]">
              <Input v-model="formValidate.account" placeholder=""></Input>
            </FormItem>
            <FormItem label="密码" prop="password" v-if="showType === 1" key="3" :rules="[{ required: true,  trigger: 'blur' }]">
                <SetPassword v-model="formValidate.password" />
            </FormItem>
            <FormItem label="角色" prop="userRoleId" key="4" :rules="[{ required: true, message: '请选择角色', trigger: 'change' }]">
              <Select v-model="formValidate.userRoleId"  transfer max-tag-count="1">
                <Option v-for="item in roleList" :value="item.id" :key="item.id" :label="item.description">
                  <span class="cmr10" >{{ item.name }}</span>
                  <span style="color: #ccc">{{ item.description }}</span>
                </Option>
              </Select>
            </FormItem>
            <FormItem label="负责人姓名" prop="personName" key="5">
              <Input v-model="formValidate.personName" placeholder=""></Input>
              <!--              <Select v-model="formValidate.submarketCode" placeholder="选择市场名称" clearable filterable>-->
              <!--                <Option v-for="item in marketNameList" :value="item.value" :key="item.value">{{ item.title }}</Option>-->
              <!--              </Select>-->
            </FormItem>
            <FormItem label="手机号" prop="mobile" key="6">
              <Input v-model="formValidate.mobile" placeholder=""></Input>
            </FormItem>
            <FormItem label="所属部门" prop="workName" key="7">
              <Input v-model="formValidate.workName" placeholder=""></Input>
            </FormItem>
            <FormItem label="担任的职位" prop="workPosition" key="8">
              <Input v-model="formValidate.workPosition" placeholder=""></Input>
            </FormItem>
            <FormItem label="工作邮箱" prop="workEmail" key="9">
              <Input v-model="formValidate.workEmail" placeholder=""></Input>
            </FormItem>
            <FormItem label="工作电话" prop="workPhone" key="10">
              <Input v-model="formValidate.workPhone" placeholder=""></Input>
            </FormItem>
            <FormItem label="传真" prop="fix" key="11">
              <Input v-model="formValidate.fix" placeholder=""></Input>
            </FormItem>

          </Form>
        </div>
        <div v-if="showType ==3" class="ml-24 mr-12">
              <Form ref="formRef"
                    :model="formValidate"
                    :rules="ruleValidate"
                    :label-width="labelWidth80">
                  <FormItem label="市场名称" prop="submarketCode" >
                      <Select v-model="formValidate.submarketName"  clearable placeholder="请选择市场名称">
                          <Option v-for="(item,index) in marketList" :value="item.submarketName" :key="item.id">{{ item.submarketName }}</Option>
                      </Select>
                  </FormItem>
                  <FormItem label="账号（市场代码）" prop="submarketCode"  >
                      <Input v-model="formValidate.submarketCode" placeholder=""></Input>
                  </FormItem>

                  <FormItem label="负责人姓名" prop="personName" >
                      <Input v-model="formValidate.personName" placeholder=""></Input>
                  </FormItem>
                  <FormItem label="手机号" prop="mobile" >
                      <Input v-model="formValidate.mobile" placeholder=""></Input>
                  </FormItem>
                  <FormItem label="所属部门" prop="workName" >
                      <Input v-model="formValidate.workName" placeholder=""></Input>
                  </FormItem>
                  <FormItem label="担任的职位" prop="workPosition" >
                      <Input v-model="formValidate.workPosition" placeholder=""></Input>
                  </FormItem>
                  <FormItem label="工作邮箱" prop="workEmail">
                      <Input v-model="formValidate.workEmail" placeholder=""></Input>
                  </FormItem>
                  <FormItem label="工作电话" prop="workPhone" >
                      <Input v-model="formValidate.workPhone" placeholder=""></Input>
                  </FormItem>
                  <FormItem label="传真" prop="fix" >
                      <Input v-model="formValidate.fix" placeholder=""></Input>
                  </FormItem>
                  <FormItem  >
                      <Button  class="float-right" type="primary" @click="searchData">搜索</Button>
                      <Button  class="float-right"  @click="resetForm">重置</Button>
                  </FormItem>
              </Form>
          </div>

      </div>
      <div class="d-flex flex-row-reverse ch60" style="align-items: center;">
        <Button v-if="showType ==1 || showType == 2" class="float-right" type="primary" @click="handleSubmit">提交</Button>
        <Button v-if="showType ==1 || showType == 2" class="float-right" @click="handleCancel">取消</Button>
      </div>
    </div>


  </div>
</template>
<script>
import {
  delMarketDataByIdsAPI,
  getAllMarketDataAPI,
  getPageDataAPI,
  getRoleDataAPI,
  exportAllMarketAccountDataAPI,
  exportBatchMarketAccountAPI,
  delByIdsMarketAccountAPI,
  updateMarketAccountAPI,
  addMarketAccountAPI,
  forbiddenMarketAccountAPI, passwordResetAPI
} from "@/api/bys/marketManagement/marketManagement";
import checkPassword from "@/views/my-components/xboot/check-password.vue";
import {resetUserPass} from "@/api";
import {deleteSchoolPersonInfo} from "@/api/bys/personInfo/school";
import SetPassword from '@/views/my-components/xboot/set-password.vue';


export default {
  components: {checkPassword,SetPassword},
  data() {
    return {
      labelWidth80:80,
        refHeight: {value: 0},
      loading: false,
      showRight: false,
      showType:3,
      rightTitle:'查询区',
      total:0,
      searchForm: {
        pageNumber: 1,
        pageSize: 10,
      },
      tableColumns:[],
      tableColumns_1: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: '序号',
          type: 'index',
          width: 60,
          align: 'center'
        },
        {
          title: '市场代码',
          key: 'submarketCode',
          align: 'center'
        },
        {
          title: '市场名称',
          key: 'submarketName',
          align: 'center'
        },
        {
          title: '负责人姓名',
          key: 'personName',
          align: 'center'
        },
        {
          title: '手机号',
          key: 'mobile',
          align: 'center'
        },
        {
          title: '工作电话',
          key: 'workPhone',
          align: 'center'
        },
        {
          title: '工作邮箱',
          key: 'workEmail',
          align: 'center'
        },
        {
          title: '状态',
          slot: 'status',
          align: 'center',
        },
        {
          title: '操作',
          slot: 'action',
          align: 'center',
          width: 180,
          fixed: "right",
        }
      ],
      tableData:[],
      formValidate: {
        account:'',
        fix:'',
        mobile:'',
        password:'',
        personName:'',
        submarketName: '',
        submarketCode: '',
        userRoleId:'',
        workEmail:'',
        workName:'',
        workPhone:'',
        workPosition:'',
      },
      ruleValidate: {
        // submarketCode: [
        //   { required: true, message: '请选择市场', trigger: 'change' }
        // ],
        // account: [{ required: true, message: '账号不能为空', trigger: 'blur' }],
        // password: [{ required: true, message: '密码不能为空', trigger: 'blur' }]
      },
      ids:'',
      //市场列表
      marketList:[],
      //角色列表
      roleList:[],
      //table选中列表
      selectDataList:[]
    }
  },
  mounted() {
    this.onRestWindow()
    window.addEventListener('resize',this.onRestWindow)
    this.getMarketData()
    this.postData()
    this.getRoleList()
  },
  beforeDestroy() {
        window.removeEventListener('resize',this.onRestWindow)
  },
  methods: {
      onRestWindow() {
          this.tableColumns = this.restTableCellWidth(this.tableColumns_1)
          this.labelWidth80 = this.searchLabelWidth(this.labelWidth80)
        
      },
      resetForm(){
          this.formValidate = {}
      },
      searchData(){
          this.searchForm.pageNumber = 1
          this.postData()
      },
    postData(){
      this.loading = true
      getPageDataAPI({...this.searchForm,...this.formValidate}).then(res => {
        console.log(res,'市场账号信息')
        if (res.success) {
          this.tableData = res?.result?.result || []
          this.total = res?.result?.total || 0
          this.loading = false
        }else{
          this.loading = false
        }
      })
    },
    //获取市场列表
    getMarketData() {
      getAllMarketDataAPI().then(res => {
        if (res.success) {
          this.marketList = res?.result || []
          console.log(res.result,'市场信息')
        }
      })
    },
    //获取角色列表
    getRoleList() {
      getRoleDataAPI().then(res => {
        if (res.success) {
          this.roleList = res.result;
          console.log(this.roleList,'role')
        }
      });
    },
    changeBackTask(v) {
        this.formValidate.account = v
    },
    selectChange(selectdata){
      console.log(selectdata,'selectChange')
      this.selectDataList = selectdata
    },
    //添加账号
    handleAdd(){
      this.$nextTick(() => {
        this.showRight = true
        this.rightTitle = '添加区'
        this.showType = 1
        this.formValidate = {
          account:'',
          fix:'',
          mobile:'',
          password:'',
          personName:'',
          submarketName: '',
          submarketCode: '',
          userRoleId:'',
          workEmail:'',
          workName:'',
          workPhone:'',
          workPosition:'',
        }
      })

    },
    //批量删除
    handleDel(type){
      if (type == 1){
        this.$Modal.confirm({
          title: '确认删除',
          content: '您确认要删除该市场用户?',
          // loading: true,
          onOk: () => {
            delByIdsMarketAccountAPI({ids:this.ids}).then(res => {
              if(res.success){
                this.$message.success(res.message)
                this.postData()
              }
            })
          }
        });

      }
      if (type == 2){
        console.log(this.selectDataList,'this.selectDataList')
        if (this.selectDataList.length == 0){
          this.$message.warning('您还未选择要删除的数据')
        }else{
          this.$Modal.confirm({
            title: '确认删除',
            content: '您确认要删除所选的 ' + this.selectDataList.length + ' 条数据?',
            // loading: true,
            onOk: () => {
              this.ids = this.selectDataList.map((obj)=>{return obj.id}).join(",");
              delByIdsMarketAccountAPI({ids:this.ids}).then(res => {
                if(res.success){
                  this.$message.success(res.message)
                  this.postData()
                }
              })
            }
          });

        }
      }


    },
    //重置用户密码
    handleResetPassword(){
      if (this.selectDataList.length <= 0) {
        this.$Message.warning('您还未选择要重置密码的用户');
        return;
      }
      this.$refs.checkPass.show();
    },
    resetPass(e, i) {
      this.$Modal.confirm({
        title: '确认重置',
        content: '您确认要重置所选的 ' + this.selectDataList.length + ' 条用户数据密码为' + i + '吗？',
        loading: true,
        onOk: () => {
          let ids = '';
          this.selectDataList.forEach(function (e) {
            ids += e.id + ',';
          });
          ids = ids.substring(0, ids.length - 1);
          passwordResetAPI({ ids: ids, passWord: i }).then(res => {
            this.$Modal.remove();
            if (res.success) {
              this.$Message.success('操作成功');
              this.postData()
            }
          });
        }
      });
    },
    //导入数据
    handleImport(){},
    //导出所选数据
    handleExportSelection(){
      if (this.selectDataList.length <= 0){
        this.$message.warning('您还未选择要导出的数据')
      }else {
        this.ids = this.selectDataList.map((obj) => {
          return obj.id
        }).join(",");
        exportBatchMarketAccountAPI({ids: this.ids}).then((res) => {
          // type的格式可以可以设置，可以把appcation/json设置进去，然后设置导出的类型
          const blob = new Blob([res], {type: 'charset=utf-8'});
          let url = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.style.display = 'none';
          link.href = url;
          link.setAttribute('download', '市场账号信息.xlsx');
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link); // 删除节点
          window.URL.revokeObjectURL(url); //释放该 url
        })
      }
    },
    //导出全部数据
    handleExportAll(){
      exportAllMarketAccountDataAPI().then((res) => {
        // type的格式可以可以设置，可以把appcation/json设置进去，然后设置导出的类型
        const blob = new Blob([res], { type: 'charset=utf-8' });
        let url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', '市场账号信息.xlsx');
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link); // 删除节点
        window.URL.revokeObjectURL(url); //释放该 url
      })
    },
    //删除
    deleteData(data) {
      this.ids = data.id
      this.handleDel(1)
    },
    //编辑
    editData(data) {
      this.$nextTick(() => {
        this.showRight = true
        this.rightTitle = '编辑区'
        this.showType = 2
        this.formValidate = data
      })

    },
    //禁用启用
    forbidden(data) {
      forbiddenMarketAccountAPI({id:data.id}).then((res) => {
        if (res.success){
          this.$message.success(res.message)
          this.postData()
        }
      })
    },
    //提交
    handleSubmit(){

      this.$refs.formRef.validate (valid => {

        if (valid) {
          if (this.formValidate.submarketCode){
            let a= this.marketList.filter(e => e.submarketCode == this.formValidate.submarketCode)
            this.formValidate.submarketName = a[0].submarketName
          }
          if (this.showType == 1){
            addMarketAccountAPI(this.formValidate).then(res => {
              if (res.success) {
                this.showRight = false
                this.$message.success('添加成功！')
                console.log(1111)
                this.postData()

              }
            })
          }
          if (this.showType == 2){
            updateMarketAccountAPI(this.formValidate).then(res => {
              if (res.success) {
                this.showRight = false
                this.$message.success('修改成功！')
                this.postData()

              }
            })
          }

        }else{
          console.log('填写')
        }
      })
    },
    //取消
    handleCancel(){
      this.formValidate = {}
      // this.showRight = false
        this.showType = 3
        this.rightTitle = '查询区'
    },
    //分页
    changePage(v) {
      this.searchForm.pageNumber = v;
      this.postData();
      this.clearSelectAll();
    },
    changePageSize(v) {
      this.searchForm.pageSize = v;
      this.postData();
    },
  }
}
</script>
<style lang="less" scoped>
.edit-table {
  width: 330px;
  background-color: #fff;
}

.hidden-table {
  width: 0;
  display: none;
}
.ch60 {
  height: 60px
}
.cw40 {
  width: 40px
}
.ch02 {
  height: calc(100% - 120px)
}
.cw400 {
  width: 400px;background-color: #ffffff
}

.ch03 {
  height: calc(100% - 60px)
}

.cmr10 {
  margin-right: 10px
}
.cscolle {
  overflow-y: auto;
}

@media  (min-width: 1921px) and (max-width: 3440px)  {
    /deep/ .ivu-table .ivu-table-fixed-right{
        height: 100% !important;
    }
    /deep/ .ivu-table .ivu-table-fixed-right  .ivu-table-fixed-body {
        height: 100% !important;
    }
  
}
</style>
